package com.jd.jstable.strategy.route;

import com.jd.jstable.exception.PipelineException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Created by chenyipu on 2018/1/22.
 */
@Service
public class ParameterConvertor {

    public Object[] convert(Object[] args, int parameterCount, String param) throws PipelineException {
        List<Integer> indexLeft = null;
        List<Integer> indexRight = null;
        if (StringUtils.isEmpty(param)) {
            indexLeft = new ArrayList<>();
            indexRight = new ArrayList<>();
        } else {
            String[] pipeline = param.split("=>");
            if (pipeline.length != 2) {
                throw new PipelineException("pipeline length U configured around => is wrong.");
            }

            if (indexLeft == null) {
                indexLeft = new ArrayList<>();
                for (String e : pipeline[0].split("-")) {
                    indexLeft.add(Integer.parseInt(e));
                }
            }
            if (indexRight == null) {
                indexRight = new ArrayList<>();
                for (String e : pipeline[1].split("-")) {
                    indexRight.add(Integer.parseInt(e));
                }
            }
        }
        if (!Objects.equals(indexLeft.size(), indexRight.size())) {
            throw new PipelineException("pipeline arg index length U configured around => is not equal.");
        }

        Object[] newArgs = new Object[parameterCount];
        for (int index = 0; index < indexLeft.size(); index++) {
            newArgs[indexRight.get(index)] = args[indexLeft.get(index)];
        }
        return newArgs;
    }
}
